package com.rocky.project.mvc;

import java.io.IOException;
import java.util.Collection;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.opensymphony.webwork.ServletActionContext;
import com.opensymphony.webwork.dispatcher.WebWorkResultSupport;
import com.opensymphony.xwork.ActionInvocation;
import com.rocky.project.action.base.BaseAction;

public class AjaxJsonResult extends WebWorkResultSupport {	
	private static final long serialVersionUID = -3778230771704661631L;
	protected Log log = LogFactory.getLog(AjaxJsonResult.class);
	public void doExecute(String location, ActionInvocation invocation)
			throws IOException {
		try {
			BaseAction baseAction = (BaseAction) invocation.getAction();
			Collection c = baseAction.getActionMessages();			
			if(c!=null && !c.isEmpty()){
				baseAction.getAjaxResultMap().put("success", false);
				baseAction.getAjaxResultMap().put("errors", c);	
				log.info("Sorry!success:false,errors :"+c.size());
			}else{
				baseAction.getAjaxResultMap().put("success", true);
				log.info("congriturations!success:true");
			}			
			ServletActionContext.getResponse().setContentType("text/plain charset=utf-8");
			ServletActionContext.getResponse().getWriter().write(JSONObject.fromObject(baseAction.getAjaxResultMap(), baseAction.getJsonConfig()).toString());
		} catch (Exception e) {
			ServletActionContext.getResponse().setContentType("text/plain charset=utf-8");
			ServletActionContext.getResponse().getWriter().write("{success:false,errors:'Sorry,AjaxJsonResult error happen!'}");
			log.info(e);
			log.info("Sorry, error happen in class: AjaxJsonResult!");
		}
	}
}
